import flet as ft
from flet_restyle import FletReStyle, FletReStyleConfig
from flet_navigator import PageData, render, anon, route


@route("/")
def main(pg: PageData):
    page = pg.page
    page.title = "markdown editor"
    restyle_config = FletReStyleConfig()
    restyle_config.custom_title_bar_title = "Markdown Editor"
    restyle_config.transparent_background = False

    FletReStyle.apply_config(page, restyle_config)

    def update_preview(e):
        """
        Update markdown preview
        :param e: event
        :type e: ControlEvent
        """
        md.value = text_field.value
        page.update()

    text_field = ft.TextField(
        value="",
        multiline=True,
        expand=True,
        border_color=ft.colors.TRANSPARENT,
        on_change=update_preview,
    )
    md = ft.Markdown(
        value=text_field.value,
        selectable=True,
        extension_set="githubWeb",
        on_tap_link=lambda e: page.launch_url(e.data),
    )
    page.add(
        ft.Row(
            controls=[
                text_field,
                ft.VerticalDivider(color=ft.colors.RED),
                ft.Container(
                    ft.Column([md], scroll="hidden"),
                    expand=True,
                    alignment=ft.alignment.top_left,
                ),
            ],
            vertical_alignment=ft.CrossAxisAlignment.START,
            expand=True,
        )
    )


@route("second_page")
def second_page(pg: PageData) -> None:
    pg.add(ft.Text("Main Page!"))


ft.app(anon(render))
